//图片放大镜组件的自定义指令
import { getStyle } from "../utils/DomUtil.js";
export default {
  mounted(el) {
    // 获取需要操作的各种元素
    const mageEl = el;
    const magView = el.querySelector(".mag-inner");
    const magImg = el.querySelector(".mag-img");
    const width = getStyle(mageEl, "width");
    const height = getStyle(mageEl, "height");
    //放大镜的宽度
    const magWidth = getStyle(magView, "width");
    //放大镜的高度
    const magHeight = getStyle(magView, "height");

    // console.log(`获取到的数据是:${width}-${height},${imgWidth}-${imgHeight}`);
    //初始化方法
    const init = () => {
      bindEvent();
    };

    //绑定事件函数
    const bindEvent = () => {
      mageEl.addEventListener(
        "mouseover",
        (e) => {
          magView.className += " show";
          showMagInner(e);
          document.addEventListener("mousemove", handleMouseMove, false);
        },
        false
      );
      mageEl.addEventListener("mouseout", handleMouseOut, false);
    };

    //鼠标移动的事件
    const handleMouseMove = (e) => {
      showMagInner(e);
    };

    //鼠标移出的事件
    const handleMouseOut = () => {
      magView.className = "mag-inner";
      document.removeEventListener("mousemove", handleMouseMove, false);
    };

    //获取当前放大镜显示的位置   moveX moveY是边界位置
    const getPostion = (e) => {
      //获取当前组件的左边距和上边距
      const currLeft = mageEl.offsetLeft;
      const currTop = mageEl.offsetTop;
      return {
        x: e.pageX - currLeft - magWidth / 2,
        y: e.pageY - currTop - magHeight / 2,
        moveX: e.pageX - currLeft,
        moveY: e.page - currTop,
      };
    };

    //显示放大镜的方法
    const showMagInner = (e) => {
      const { x, y, moveX, moveY } = getPostion(e);
      //处理边界问题
      if (moveX < 0 || moveY < 0 || moveX > width || moveY > height) {
        magView.className = "mag-inner";
        document.removeEventListener("mousemove", handleMouseMove, false);
      }

      magView.style.left = x + "px";
      magView.style.top = y + "px";
      //反方向移动放大镜内部的图片,确保图片放大的位置正确
      magImg.style.left = -x + "px";
      magImg.style.top = -y + "px";
    };

    init();
  },
};
